import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import pinia from '@/stores' // 引入Pinia实例
import { useUserStore } from '@/stores/userStore' // 引入用户Store
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about', // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/person',
      name: 'person', // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/personView.vue'),
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore(pinia) // 使用Pinia Store
  console.log(to.name)
  console.log(userStore.$state.name)
  // 检查目标路由是否需要登录
  if (to.name != 'home') {
    if (!userStore.$state.name) {
      // 如果未登录，则重定向到首页或登录页
      next({
        path: '/',
        query: { redirect: to.fullPath }, // 将目标路径作为查询参数传递
      })
    } else {
      next() // 已登录，继续导航
    }
  } else {
    next() // 不需要登录，继续导航
  }
})

export default router
